package com.example.demo.leetcode.classics150;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _107单词搜索
 * @description
 * @date 2023/08/12 21:32
 * <p>
 * ******************************************************
 */
public class _107单词搜索 {

    boolean result = false;
    int[][] helper = new int[][]{{0, -1}, {0, 1}, {-1, 0}, {1, 0}};

    public boolean exist(char[][] board, String word) {
        StringBuilder w = new StringBuilder(word);
        int m = board.length;
        int n = board[0].length;

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (!result) {
                    backtrack(board, w, i, j);
                }
            }
        }
        return result;
    }

    private void backtrack(char[][] board, StringBuilder word, int i, int j) {

        if (word.length() == 0) {
            result = true;
            return;
        }

        int m = board.length, n = board[0].length;
        if (i < 0 || i >= m || j < 0 || j >= n) {
            return;
        }

        char c = board[i][j];
        if (c == '#' || c != word.charAt(0)) {
            return;
        }
        char delete = word.charAt(0);
        word.deleteCharAt(0);
        board[i][j] = '#';
        for (int[] item : helper) {
            backtrack(board, word, i + item[0], j + item[1]);
        }
        word.insert(0, delete);
        board[i][j] = c;
    }

    public static void main(String[] args) {
        _107单词搜索 s = new _107单词搜索();
        System.out.println(s.exist(new char[][]{{'A','B','C','E'},{'S','F','C','S'},{'A','D','E','E'}}, "SEC"));
    }
}
